<template>
	<view>
		<view class="header-bg">
			<view class="acea-row row-right">
				<view class="look-detail" @click="toLookDetail">查看明细</view>
			</view>
			<view class="title">我的金币</view>
			<view class="num">{{coin}}</view>
			<view class="text">购物时可直接支付抵扣，10金币≈1元</view>
		</view>
		<view class="acea-row row-middle row-center module-title">
			<view>-</view>
			<view>金币充值</view>
			<view>-</view>
		</view>
		<view class="acea-row row-between list">
			<view class="acea-row row-column row-center row-middle item" :class="itemOn==index?'item-on':''"
				v-for="(item,index) in list" :key="index" @click="itemOn=index">
				<view class="tag">赠送{{item.giveMoney}}</view>
				<view class="acea-row row-middle row-center gold-coin">
					<image src="@/static/images/goldcoin_icon.png" mode=""></image>
					<view>{{Number(item.price)*10 + Number(item.giveMoney)}}</view>
				</view>
				<view class="money">￥{{item.price}}</view>
			</view>
		</view>
		<view class="acea-row row-middle input-box" style="flex-wrap: nowrap;">
			<view>￥</view>
			<input type="number" placeholder="请手动输入充值金额" v-model="money" placeholder-class="placeholder-class"
				@input="onInput">
		</view>
		<view class="introduce">说明：金币属于虚拟商品，一经购买概不退还</view>
		<view class="submit-btn" @click="submitSub">
			立即充值
		</view>
		<view class="uni-p-b-98">

		</view>
	</view>
</template>

<script>
	import {
		rechargeRoutine,
		rechargeWechat,
		getRechargeApi,
		transferIn,
		appWechat,
		alipayFull,
		rechargeCreateApi,
	} from '@/api/user.js';
	import {
		Debounce
	} from '@/utils/validate.js'
	import {
		getCoinList,
		getIndividual
	} from "@/api/api.js"
	import {
		mapGetters
	} from "vuex";
	import {
		toLogin
	} from '@/libs/login.js';
	let app = getApp();
	export default {
		data() {
			return {
				list: [],
				itemOn: 0,
				money: '',
				coin: 0,
				payType: 'weixin',
				noticeList: [],
				rechar_id: 0
			};
		},
		onLoad() {
			if (this.isLogin) {
				this.getRecharge();
				this.getConin()
			} else {
				toLogin();
			}
		},
		computed: mapGetters(['isLogin', 'systemPlatform', 'userInfo']),
		watch: {
			isLogin: {
				handler: function(newV, oldV) {
					if (newV) {
						this.getRecharge();
					}
				},
				deep: true
			},
			itemOn: {
				handler: function(newV, oldV) {
					this.money = this.list[newV].price;
				},
				deep: true
			}
		},
		methods: {
			onInput(e) {
				let val = e.target.value.replace(/(^\s*)|(\s*$)/g, "")
				if (!val) {
					this.val = '';
					return
				}
				var reg = /[^\d.]/g
				// 只能是数字和小数点，不能是其他输入
				val = val.replace(reg, "")
				// // 保证第一位只能是数字，不能是点
				val = val.replace(/^\./g, "");
				// // 小数只能出现1位
				val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
				// // 小数点后面保留2位
				val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
				this.$nextTick(() => {
					this.money = val;
				})
			},
			toLookDetail() {
				wx.navigateTo({
					url:'/pages/users/user_integral/index'
				});
			},
			/**
			 * 充值额度选择
			 */
			getRecharge() {
				getRechargeApi()
					.then(res => {
						console.log('res--', res)
						this.list = res.data.packageList;
						if (this.list.length > 0) {
							this.rechar_id = this.list[0].id;
							this.money = this.list[0].price;
							console.log(this.money)
						}
						this.noticeList = res.data.noticeList || [];
					})
					.catch(res => {
						this.$util.Tips({
							title: res
						});
					});
			},
			/*
			 * 用户充值
			 */
			submitSub: Debounce(function(e) {
				console.log(e.detail);
				let that = this
				// 转入余额

				uni.showLoading({
					title: '正在支付',
				})
				let money = parseFloat(that.money);
				console.log('money', that.money)

				if (Number.isNaN(money)) {
					return that.$util.Tips({
						title: '充值金额必须为数字'
					});
				}
				if (money <= 0) {
					return that.$util.Tips({
						title: '充值金额不能为0'
					});
				}
				if (money > 50000) {
					return that.$util.Tips({
						title: '充值金额最大值为50000'
					});
				}

				if (that.payType == 'alipay') {
					// #ifdef H5
					that.payChannel = 'alipay';
					// #endif
					// #ifdef APP-PLUS
					that.payChannel = 'alipayApp';
					// #endif
				} else {
					// #ifdef H5
					that.payChannel = that.$wechat.isWeixin() ? "public" : "h5";
					// #endif
					// #ifdef MP
					that.payChannel = "mini";
					// #endif
					// #ifdef APP-PLUS
					cpayChannel = that.systemPlatform === 'ios' ? 'weixinAppIos' : 'weixinAppAndroid';
					// #endif
				}
				console.log(money, that.payChannel)
				rechargeCreateApi({
					payChannel: that.payChannel,
					price: money,
					payType: that.payType,
					groupDataId: that.rechar_id,
					type : 0,
				}).then(res => {
					console.log('res', res)
					uni.hideLoading();
					that.pay(res);
				}).catch(err => {
					uni.hideLoading();
					return that.$util.Tips({
						title: err
					})
				});
			}),
			getConin() {
				getIndividual().then(res => {
					if (res.code == 200) {
						this.coin = res.data.integral;
					}

				})
			},
			pay(res) {
				let that = this
				switch (that.payType) {
					case 'weixin':
						// #ifdef APP-PLUS
						let jsConfig = res.data.jsConfig;
						uni.requestPayment({
							provider: 'wxpay',
							orderInfo: {
								"appid": jsConfig.appId, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
								"noncestr": jsConfig.nonceStr, // 随机字符串
								"package": "Sign=WXPay", // 固定值
								"partnerid": jsConfig.partnerid, // 微信支付商户号
								"prepayid": jsConfig.packages, // 统一下单订单号
								"timestamp": Number(jsConfig.timeStamp), // 时间戳（单位：秒）
								"sign": that.systemPlatform === 'ios' ? 'MD5' : jsConfig.paySign // 签名，这里用的 MD5 签名
							}, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
							success: function(res) {
								 that.$util.Tips({
									title: '支付成功',
									icon: 'success'
								});
								that.getConin();
							},
							fail: function(err) {
								return that.$util.Tips({
									title: '支付失败'
								});
							},
							complete: function(res) {
								if (res.errMsg == 'requestPayment:cancel') return that.$util.Tips({
									title: '取消支付'
								});
							}
						})
						// #endif

						// #ifdef MP
						let jsConfig = res.data.jsConfig;
						console.log(jsConfig)
						uni.requestPayment({
							timeStamp: jsConfig.timeStamp,
							nonceStr: jsConfig.nonceStr,
							package: jsConfig.packages,
							signType: jsConfig.signType,
							paySign: jsConfig.paySign,
							success: function(res) {
								 that.$util.Tips({
									title: '支付成功',
									icon: 'success'
								});
								that.getConin();
							},
							fail: function(err) {
								return that.$util.Tips({
									title: '支付失败'
								});
							},
							complete: function(res) {
								if (res.errMsg == 'requestPayment:cancel') return that.$util.Tips({
									title: '取消支付'
								});
							}
						})
						// #endif
						// #ifdef H5
						let jsConfig = res.data.jsConfig;
						let orderNo = res.data.orderNo;
						let data = {
							timestamp: jsConfig.timeStamp,
							nonceStr: jsConfig.nonceStr,
							package: jsConfig.packages,
							signType: jsConfig.signType,
							paySign: jsConfig.paySign
						};
						if (that.payChannel == "h5") {
							uni.hideLoading();
							that.$util.Tips({
								title: '支付成功'
							});
							that.getConin();
							// setTimeout(() => {
							// 	location.href = jsConfig.mwebUrl;
							// }, 100)
						} else {
							that.$wechat.pay(data)
								.finally(() => {
									that.$util.Tips({
										title: '支付成功',
										icon: 'success'
									});
									that.getConin();
								})
								.catch(function(err) {
									return that.$util.Tips({
										title: '支付失败'
									});
								});
						}
						// #endif
						break;
					case 'alipay':
						// alipayFull
						// #ifdef APP-PLUS
						let alipayRequest = res.data.alipayRequest;
						uni.requestPayment({
							provider: 'alipay',
							orderInfo: alipayRequest,
							success: (e) => {
								 that.$util.Tips({
									title: '支付成功',
									icon: 'success'
								};
								that.getConin();
							},
							fail: (e) => {
								return that.$util.Tips({
									title: '支付失败'
								});
							},
							complete: () => {
								uni.hideLoading();
							},
						});
						// #endif
						// #ifdef H5
						if (that.$wechat.isWeixin()) {
							uni.redirectTo({
								url: `/pages/users/alipay_invoke/index?price=${money}&rechar_id=${that.rechar_id}&type=users`
							});
						} else {
							that.formContent = res.data.alipayRequest;
							that.$nextTick(() => {
								document.forms['punchout_form'].submit();
							})
						}
						// #endif
						break;
				}
			},
			addMoney() {
				//this.money = this.money.replace(/[^\d]/g, '').replace(/^0{1,}/g, '');
			}
		}
	}
</script>

<style lang="scss">
	.header-bg {
		width: 100%;
		height: 476rpx;
		padding: 60rpx 60rpx 100rpx 60rpx;
		background: url('https://image.shanghepu.com/cdn/images/globBg.png');
		background-position: center;
		background-repeat: no-repeat;
		background-size: 100% 100%;
	}

	.look-detail {
		position: relative;
		padding-right: 12rpx;
		font-size: 26rpx;
		font-weight: 400;
		color: #FFFFFF;

		&::after {
			content: '';
			display: block;
			position: absolute;
			right: 0rpx;
			top: 50%;
			width: 12rpx;
			height: 12rpx;
			border-top: 1px solid #ffffff;
			border-right: 1px solid #ffffff;
			transform: rotate(45deg) translateY(-50%);
		}
	}

	.title {
		text-align: center;
		font-size: 32rpx;
		font-family: Source Han Sans CN;
		font-weight: 400;
		color: #FFFFFF;
	}

	.num {
		text-align: center;
		padding: 30rpx 0;
		font-size: 92rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #FFFFFF;
	}

	.text {
		text-align: center;
		font-size: 24rpx;
		font-family: Source Han Sans CN;
		font-weight: 400;
		color: #FFFFFF;
	}

	.module-title {
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #686868;
		position: relative;
		margin-top: -50rpx;
	}

	.list {
		padding: 30rpx;

		&::after {
			display: block;
			content: '';
			width: 209rpx;
		}

		.item {
			width: 209rpx;
			height: 150rpx;
			background: #FFFFFF;
			border: 2px solid #E3E3E3;
			border-radius: 10rpx;
			position: relative;
			margin-bottom: 24rpx;
		}

		.item-on {
			border: 3px solid #EE212D;
		}

		.gold-coin {
			font-size: 40rpx;
			font-family: Arial;
			font-weight: bold;
			color: #040101;

			image {
				width: 37rpx;
				height: 37rpx;
				margin-right: 12rpx;
			}
		}

		.money {
			text-align: center;
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #AAAAAA;
		}

		.tag {
			width: 158rpx;
			height: 39rpx;
			line-height: 39rpx;
			font-size: 24rpx;
			font-family: Source Han Sans CN;
			font-weight: 400;
			color: #FFFFFF;
			background: linear-gradient(150deg, #F52D37, #EE212D);
			border-radius: 20rpx 20rpx 20rpx 0rpx;
			position: absolute;
			top: -20rpx;
			left: -10rpx;
			text-align: center;

			&::before {
				content: '';
				display: block;
				width: 0rpx;
				height: 0rpx;
				position: absolute;
				bottom: -10rpx;
				left: 0;
				border-color: #BA0C16 transparent transparent transparent;
				border-style: solid;
				border-width: 12rpx 10rpx 0 0;
				transform: rotateY(180deg);
			}
		}
	}

	.input-box {
		margin: 0 30rpx;
		height: 80rpx;
		padding: 0 30rpx;
		background: #FFFFFF;
		border: 2px solid #E3E3E3;
		border-radius: 10rpx;
		font-size: 38rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #040101;

		input {
			padding-left: 12rpx;
		}

		.placeholder-class {
			font-size: 26rpx;
			font-family: PingFang SC;
			font-weight: 400;
			color: #D8D8D8;
		}
	}

	.introduce {
		padding: 30rpx;
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #919191;
	}

	.submit-btn {
		margin: auto;
		width: 701rpx;
		height: 100rpx;
		background: #EE212D;
		border-radius: 10rpx;
		font-size: 34rpx;
		font-family: PingFangSC;
		font-weight: 400;
		color: #FFFFFF;
		text-align: center;
		line-height: 100rpx;
	}
</style>
<style>
	page {
		background: #ffffff !important;
	}
</style>